import pygame
import random
from .bullet import Bullet

ENEMY_CONFIG = {
    "enemy_1": {"hp": 1, "speed": 1, "fire_rate": 30},
    "enemy_2": {"hp": 2, "speed": 1, "fire_rate": 30},
    "enemy_3": {"hp": 3, "speed": 1, "fire_rate": 30},
    "enemy_4": {"hp": 4, "speed": 1, "fire_rate": 30},
}


class EnemyTank:
    def __init__(self, x, y, enemy_type="enemy_1"):
        self.type = enemy_type
        self.config = ENEMY_CONFIG[enemy_type]
        self.hp = self.config["hp"]
        self.speed = self.config["speed"]
        self.fire_rate = self.config["fire_rate"]
        self.image = pygame.image.load(f"images/{enemy_type}_1.png")
        self.rect = self.image.get_rect(topleft=(x, y))
        self.direction = random.choice(["up", "down", "left", "right"])
        self.fire_count = 0
        self.bullets = []

    def move(self, game_map):
        new_rect = self.rect.copy()
        if self.direction == "up":
            new_rect.y -= self.speed
        elif self.direction == "down":
            new_rect.y += self.speed
        elif self.direction == "left":
            new_rect.x -= self.speed
        elif self.direction == "right":
            new_rect.x += self.speed

        if not game_map.check_collision(new_rect):
            self.rect = new_rect

        if random.randint(0, 100) < 2:
            self.direction = random.choice(["up", "down", "left", "right"])

    def fire(self):
        self.fire_count += 1
        # 检查是否已经有活跃的子弹
        if self.fire_count >= self.fire_rate and len([b for b in self.bullets if b.active]) == 0:
            self.fire_count = 0
            bullet = Bullet(self.rect.centerx, self.rect.centery, self.direction, 5, "enemy")
            self.bullets.append(bullet)

    def update(self, game_map):
        self.move(game_map)
        self.fire()
        self.bullets = [b for b in self.bullets if b.active]
        for bullet in self.bullets:
            bullet.update(game_map)

    def draw(self, screen):
        screen.blit(self.image, self.rect)
        for bullet in self.bullets:
            bullet.draw(screen)

    def hit(self, damage):
        self.hp -= damage
        return self.hp <= 0